import {
    _decorator,
    Component,
    MeshRenderer,
    Mesh,
    Material,
    utils,
    Texture2D,
    Vec3,
    Vec2,
    Color,
    Node,
    primitives,
    Sprite,
} from 'cc';
const { ccclass, property } = _decorator;

@ccclass('ScrollForegroundMesh')
export class ScrollForegroundMesh extends Component {
    @property(Material)
    public material: Material | null = null;

    @property(Texture2D)
    public mainTexture: Texture2D | null = null;

    public vertexSpeeds: number[] = [0.8, 1.0, 1.2, 1.0];

    private _offsetX = 0;

    start() {
        if (!this.material) {
            console.error('material is null');
            return;
        }
        this._createQuad();
    }

    update(dt: number) {
        if (!this.material) return;
        this._offsetX += dt * 0.1;
        const ox = ((this._offsetX % 1) + 1) % 1;
        this.material.setProperty('offset', [ox, 0]);
    }

    private _createQuad() {
        const positions = [-1, -1, 0, 1, -1, 0, 1, 1, 0, -1, 1, 0];
        const uvs = [0, 0, 1, 0, 1, 1, 0, 1];
        const indices = [0, 1, 2, 0, 2, 3];
        const colors: number[] = [];
        for (let i = 0; i < 4; i++) {
            const speed = this.vertexSpeeds[i] ?? 1.0;
            colors.push(1, 1, 1, 1); // r=1, g=1, b=1, a = speed
        }

        const geometry: primitives.IGeometry = {
            positions,
            uvs,
            colors,
            indices,
        };

        const mesh: Mesh = utils.MeshUtils.createMesh(geometry);

        const mr =
            this.node.getComponent(MeshRenderer) ||
            this.node.addComponent(MeshRenderer);
        mr.mesh = mesh;
        const mat = this.material!;
        // if (this.mainTexture) {
        //     mat.setProperty('mainTexture', this.mainTexture);
        // }
        mr.setSharedMaterial(mat, 0);
    }
}
